package edu.avans.hartigehap.web.frontend.controller;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.avans.hartigehap.domain.*;
import edu.avans.hartigehap.service.*;
import edu.avans.hartigehap.web.form.Message;
import edu.avans.hartigehap.web.util.UrlUtil;
import edu.avans.hartigehap.web.util.FrontendBillInterceptor;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.Valid;
import javax.servlet.http.HttpServletResponse;


@RequestMapping("restaurants/{restaurantName}/order")
@Controller
public class OrderFrontendController {
		
	final Logger logger = LoggerFactory.getLogger(OrderFrontendController.class);
	
	@Autowired
	private MessageSource messageSource;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private RestaurantService restaurantService;
	@Autowired
	private DiningTableService diningTableService;
	@Autowired
	private BillService billService;
	
	// mapping to "/" is not RESTful, but is for bootstrapping!
			
	@RequestMapping(value = {""}, method = RequestMethod.GET)
	public String beginOrdering(
			Customer customer,
			HttpServletRequest request,
			Model uiModel, 
			@PathVariable("restaurantName") String restaurantName
			) {
		
		// warmup stuff
		Collection<Restaurant> restaurants = restaurantService.findAll();
		uiModel.addAttribute("restaurants", restaurants);
		
		Long billId = (Long) request.getAttribute("billId");
		Bill bill = billService.findBillById(billId);
		
		uiModel.addAttribute("bill", bill);
		
		Restaurant restaurant = restaurantService.fetchWarmedUp(restaurantName);
		uiModel.addAttribute("restaurant", restaurant);
		
		uiModel.addAttribute("customer", customer);
		
		
		return "frontend/hartigehap/order";
	}

	@RequestMapping(value = {""}, method = RequestMethod.PUT)
	public String submitOrder(
			HttpServletRequest request,
			HttpServletResponse response,
			Model uiModel, 

			@PathVariable("restaurantName") String restaurantName,
			@ModelAttribute("customer") @Valid Customer customer,
			BindingResult bindingResult,
			RedirectAttributes redirectAttributes,
			Locale locale
			) throws StateException, EmptyBillException {
		
		// warmup stuff
		Collection<Restaurant> restaurants = restaurantService.findAll();
		uiModel.addAttribute("restaurants", restaurants);
		
		Restaurant restaurant = restaurantService.fetchWarmedUp(restaurantName);
		uiModel.addAttribute("restaurant", restaurant);
		
		Long billId = (Long) request.getAttribute("billId");
		logger.info("billId = " + billId);
		Bill bill = billService.findBillById(billId);
		logger.info("bill = " + bill);
		
		/**
		 * Eerst user aanmaken
		 */

		logger.info("Creating customer: " + customer.getFirstName() + " " + customer.getLastName());	
		logger.info("Binding Result target: " + (Customer) bindingResult.getTarget()); 
		logger.info("Binding Result: " + bindingResult);
		
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute(
					"message",
					new Message("error", messageSource.getMessage(
							"customer_save_fail", new Object[] {}, locale)));
			uiModel.addAttribute("customer", customer);
			uiModel.addAttribute("bill", bill);
			return "frontend/hartigehap/order";
		}
		
		/*
		uiModel.asMap().clear();
		redirectAttributes.addFlashAttribute(
				"message",
				new Message("success", messageSource.getMessage(
						"customer_save_success", new Object[] {}, locale)));*/
		logger.info("Customer id: " + customer.getId());

		
		
		/**
		 * Bestelling plaatsen
		 */
		
		try {
			billService.submitOrder(bill, customer, restaurant);
			
			//customerService.save(customer);
			//restaurantService.save(restaurant);
			uiModel.addAttribute("bill", bill);
			
			FrontendBillInterceptor.deleteBillId(response);
			
			return "frontend/hartigehap/order/submitted";
		} catch(StateException e){
			uiModel.addAttribute(
					"message",
					new Message("error", messageSource.getMessage(
							"order_save_fail", new Object[] {}, locale)));
			uiModel.addAttribute("customer", customer);
			return "frontend/hartigehap/order";
		}
	}
	
	
	@RequestMapping(value = {""}, method = RequestMethod.POST)
	public String createOrder(
			@ModelAttribute("customer")
			@Valid Customer customer, BindingResult bindingResult,
			RedirectAttributes redirectAttributes, Locale locale,
			HttpServletRequest request,
			Model uiModel, HttpServletRequest httpServletRequest
			) {
		
		
		/**
		 * Eerst user aanmaken
		 */

		logger.info("Creating customer: " + customer.getFirstName() + " " + customer.getLastName());	
		logger.info("Binding Result target: " + (Customer) bindingResult.getTarget()); 
		logger.info("Binding Result: " + bindingResult);
		
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute(
					"message",
					new Message("error", messageSource.getMessage(
							"customer_save_fail", new Object[] {}, locale)));
			uiModel.addAttribute("customer", customer);
			return "hartigehap/editcustomer";
		}
		
		
		uiModel.asMap().clear();
		redirectAttributes.addFlashAttribute(
				"message",
				new Message("success", messageSource.getMessage(
						"customer_save_success", new Object[] {}, locale)));
		logger.info("Customer id: " + customer.getId());

		customerService.save(customer);
		
		
		/**
		 * Bestelling aanmaken
		 */
		
		
		return "frontend/hartigehap/order";
		//return "redirect:/forwarden-naar-een-url/";
		
		
	}

}
